package com.cuixichang.minimalism.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cuixichang.minimalism.acl.RelevanceDesign;
import com.cuixichang.minimalism.basal.base.Result;
import com.cuixichang.minimalism.basal.enums.IsEnableEnum;
import com.cuixichang.minimalism.basal.enums.ResponseCoderEnum;
import com.cuixichang.minimalism.core.security.userdetails.CredentialDetail;
import com.cuixichang.minimalism.core.security.utils.SecurityBeanUtil;
import com.cuixichang.minimalism.domain.IPermissionCommandService;
import com.cuixichang.minimalism.transfer.dto.IPermissionDTO;
import com.cuixichang.minimalism.transfer.factory.IPermissionAssembler;
import com.cuixichang.minimalism.transfer.page.IPermissionPageRequest;
import com.cuixichang.minimalism.transfer.page.IPermissionRequest;
import com.cuixichang.minimalism.transfer.vo.IPermissionVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import com.cuixichang.minimalism.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 系统权限表表控制层
 *
 * @author cuixichang
 * @date 2024-12-07
 */
@Api(tags = "系统权限表对象功能接口")
@RestController
@RequestMapping("permission")
@RequiredArgsConstructor
public class IPermissionController {

    @Autowired
    private IPermissionService iPermissionService;
    @Autowired
    private IPermissionCommandService iPermissionCommandService;
    @Autowired
    private RelevanceDesign relevanceDesign;

    @GetMapping("/info/{systemCode}/{id}")
    @ApiOperation(value = "查询权限基本信息通过ID")
    public Result<IPermissionVO> selectById(@PathVariable("id") Long id, @PathVariable("systemCode") String systemCode){
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        IPermissionDTO permission = iPermissionCommandService.selectByIdHasPreCheck(id, systemCode, credentialDetail);
        return Result.ok("查询权限信息完成", IPermissionAssembler.INSTANCT.convertVo(permission));
    }

    @GetMapping("/infoByCode/{systemCode}/{permissionCode}")
    @ApiOperation(value = "查询权限基本信息通过RoleCode")
    public Result<IPermissionVO> selectByCode(@PathVariable("permissionCode") String permissionCode, @PathVariable("systemCode") String systemCode){
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        IPermissionDTO permission = iPermissionCommandService.selectByCodeHasPreCheck(permissionCode, systemCode, credentialDetail);
        return Result.ok("查询角色信息完成", IPermissionAssembler.INSTANCT.convertVo(permission));
    }

    @DeleteMapping("/info/{systemCode}/{id}")
    @ApiOperation(value = "删除权限基本信息通过ID")
    public Result<Boolean> deleteById(@PathVariable Long id,@PathVariable("systemCode") String systemCode){
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        boolean deleteFlag = iPermissionCommandService.deleteByIdHasPreCheck(id, systemCode,credentialDetail);
        return Result.ok(ResponseCoderEnum.Success.getDesc(), deleteFlag);
    }

    @PutMapping("/info/{systemCode}/{id}")
    @ApiOperation(value = "修改角色基本信息通过ID")
    public Result<Boolean> updateById(@PathVariable Long id,@PathVariable("systemCode") String systemCode,
                                      @RequestBody IPermissionRequest request){
        IPermissionDTO dto = IPermissionAssembler.INSTANCT.convertDto(request);
        dto.setId(id);
        dto.setCreateSystemCode(systemCode);
        boolean update = iPermissionCommandService.updateByIdHasPreCheck(dto,SecurityBeanUtil.getCredentialDetail());
        return Result.ok(ResponseCoderEnum.Success.getDesc(), update);
    }

    @PostMapping("/info")
    @ApiOperation(value = "创建角色基本信息")
    public Result<IPermissionVO> insert(@RequestBody IPermissionRequest request) {
        IPermissionDTO dto = IPermissionAssembler.INSTANCT.convertDto(request);
        IPermissionDTO permission = iPermissionCommandService.insert(dto,SecurityBeanUtil.getCredentialDetail());
        return Result.ok("权限信息创建成功",IPermissionAssembler.INSTANCT.convertVo(permission));
    }

    @GetMapping("/page")
    @ApiOperation(value = "分页条件查询用户可操作权限信息")
    public Result<Page<IPermissionVO>> selectPageByConditional(IPermissionPageRequest request){
        IPermissionDTO dto = IPermissionAssembler.INSTANCT.convertDto(request);;
        Page<IPermissionDTO> iPermissionPage = iPermissionCommandService.selectPageByConditional(dto, request.getPageNo(),
                request.getPageSize(),SecurityBeanUtil.getCredentialDetail());
        Page<IPermissionVO> result = new Page<>(iPermissionPage.getCurrent(), iPermissionPage.getSize(), iPermissionPage.getTotal());
        result.setRecords(iPermissionPage.getRecords().stream().map(IPermissionAssembler.INSTANCT::convertVo).collect(Collectors.toList()));
        return Result.ok("分页查询用户权限信息完成",result);
    }

    @GetMapping("/role/{bindingStatus}/{roleId}")
    @ApiOperation(value = "角色已绑定/允许绑定权限查询")
    public Result<Page<IPermissionVO>> roleBindingPermissions(@PathVariable("bindingStatus") String bindingStatus,
                                                        @PathVariable("roleId") Long relationId,
                                                        IPermissionPageRequest request) {
        IPermissionDTO dto = IPermissionAssembler.INSTANCT.convertDto(request);
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        Page<IPermissionDTO> page = Optional.ofNullable(bindingStatus).filter(code -> IsEnableEnum.YES.getCode().toString().equals(code)).map(
                code -> iPermissionCommandService.roleHasBindingPermissions(dto, request.getPageNo(), request.getPageSize(), relationId, credentialDetail)
        ).orElseGet(() -> iPermissionCommandService.roleUnBindingPermissions(dto, request.getPageNo(), request.getPageSize(), relationId, credentialDetail));
        Page<IPermissionVO> result = new Page(page.getCurrent(),page.getSize(),page.getTotal());
        List<IPermissionDTO> records = page.getRecords();
        result.setRecords(records.stream().map(IPermissionAssembler.INSTANCT::convertVo).collect(Collectors.toList()));
        return Result.ok("查询成功",result);
    }

    @GetMapping("/router/{bindingStatus}/{routerId}")
    @ApiOperation(value = "路由已绑定/允许绑定权限查询")
    public Result<Page<IPermissionVO>> routerBindingPermissions(@PathVariable("bindingStatus") String bindingStatus,
                                                                @PathVariable("routerId") Long relationId,
                                                                IPermissionPageRequest request) {
        IPermissionDTO dto = IPermissionAssembler.INSTANCT.convertDto(request);
        CredentialDetail credentialDetail = SecurityBeanUtil.getCredentialDetail();
        Page<IPermissionDTO> page = Optional.ofNullable(bindingStatus).filter(code -> IsEnableEnum.YES.getCode().toString().equals(code)).map(
                code -> iPermissionCommandService.routerHasBindingPermissions(dto, request.getPageNo(), request.getPageSize(), relationId, credentialDetail)
        ).orElseGet(() -> iPermissionCommandService.routerUnBindingPermissions(dto, request.getPageNo(), request.getPageSize(), relationId, credentialDetail));
        Page<IPermissionVO> result = new Page(page.getCurrent(),page.getSize(),page.getTotal());
        List<IPermissionDTO> records = page.getRecords();
        result.setRecords(records.stream().map(IPermissionAssembler.INSTANCT::convertVo).collect(Collectors.toList()));
        return Result.ok("查询成功",result);
    }

    @PostMapping("/role/{bindingStatus}/{permissionId}/{roleId}")
    @ApiOperation(value = "权限绑定（解绑）角色")
    public Result<Boolean> roleBindingStatus(@PathVariable("bindingStatus") String bindingStatus,
                                             @PathVariable("roleId") Long roleId,
                                             @PathVariable("permissionId") Long permissionId){
        return Result.ok("操作成功",relevanceDesign.rolePermissionBindingStatus(roleId, permissionId, IsEnableEnum.YES.getCode().toString().equals(bindingStatus),
                SecurityBeanUtil.getCredentialDetail()));
    }

    @PostMapping("/router/{bindingStatus}/{permissionId}/{routerId}")
    @ApiOperation(value = "权限绑定（解绑）角色")
    public Result<Boolean> routerBindingStatus(@PathVariable("bindingStatus") String bindingStatus,
                                             @PathVariable("routerId") Long routerId,
                                             @PathVariable("permissionId") Long permissionId){
        return Result.ok("操作成功",relevanceDesign.routerBindingStatus(routerId, permissionId,false, IsEnableEnum.YES.getCode().toString().equals(bindingStatus),
                SecurityBeanUtil.getCredentialDetail()));
    }
}
